<?php

namespace app\admin\controller\wanlshop;

use app\common\controller\Backend;
use OSS\Model\PartInfo;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\wanlshop\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Order;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user','shop','ordergoods'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user','shop','ordergoods'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['username','nickname']);
                $row->getRelation('shop')->visible(['shopname']);
				$row->pay = model('app\admin\model\wanlshop\Pay')
					->where(['order_id' => $row['id'], 'type' => 'goods'])
					->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
					->find();
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            //更新消息状态
            $this->model->where('admin_read',1)->update(['admin_read'=>2]);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 导出
     */
    public function export()
    {
//        if ($this->request->isPost()) {
            set_time_limit(0);
            ini_set ('memory_limit', '2048M');
            //当前是否为关联查询
            $this->relationSearch = true;
            //设置过滤方法
            $this->request->filter(['strip_tags', 'trim']);
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $ids = $this->request->post('ids'); //获取数据的所有id
        //查询数据
        $wheres = [];
        if ($ids != 'all') {
            $wheres['id'] = ['in', $ids];
        }
            $total = $this->model
                ->where($where)
                ->where($wheres)
                ->order($sort, $order)
                ->count();
//            $total = 1;
            $list = $this->model
                ->where($where)
                ->where($wheres)
                ->order($sort, $order)
//                ->limit($offset, $limit)
//                ->limit(1)
                ->select();

            foreach ($list as $row) {
//                $row->getRelation('user')->visible(['username','nickname']);
//                $row->getRelation('shop')->visible(['shopname']);
                $row->pay = model('app\admin\model\wanlshop\Pay')
                    ->where(['order_id' => $row['id'], 'type' => 'goods'])
                    ->find();
                $row->user = model('app\admin\model\User')
                    ->field('id, nickname, mobile')
                    ->where(['id' => $row['user_id']])
                    ->find();
                $row->address = model('app\api\model\wanlshop\OrderAddress')
                    ->where(['order_id' => $row['id']])
                    ->order('isaddress desc')
                    ->field('name,mobile,address')
                    ->find();
            }
            $list = collection($list)->toArray();
            $newExcel = new Spreadsheet();  //创建一个新的excel文档
            $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
            $objSheet->setTitle('订单列表');  //设置当前sheet的标题
            $objSheet->getDefaultColumnDimension()->setWidth(30); // 设置默认列宽为15$sheet->getDefaultColumnDimension()->setWidth(15); // 设置默认列宽为15

            $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('K')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('M')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('N')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('O')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('P')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('Q')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('R')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('S')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('T')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('U')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('V')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('W')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('X')->setAutoSize(true);


            $objSheet->setCellValue('A1', '订单ID')
                ->setCellValue('B1', '订单编号')
                ->setCellValue('C1', '支付单号')
                ->setCellValue('D1', '支付方式')
                ->setCellValue('E1', '优惠金额')
                ->setCellValue('F1', '商品小计')
                ->setCellValue('G1', '运费')
                ->setCellValue('H1', '应收款')
                ->setCellValue('I1', '已退款金额')
                ->setCellValue('J1', '剩余金额')
                ->setCellValue('K1', '订单状态')
//                ->setCellValue('L1', '售后状态')
                ->setCellValue('L1', '下单时间')
                ->setCellValue('M1', '付款时间')
                ->setCellValue('N1', '发货时间')
                ->setCellValue('O1', '完成时间')
                ->setCellValue('P1', '快递公司')
                ->setCellValue('Q1', '快递单号')
                ->setCellValue('R1', '订单备注')
                ->setCellValue('S1', '会员ID')
                ->setCellValue('T1', '会员昵称')
                ->setCellValue('U1', '会员手机号')
                ->setCellValue('V1', '收货人姓名')
                ->setCellValue('W1', '收货人手机号')
                ->setCellValue('X1', '收货地址');
            /*--------------开始从数据库提取信息插入Excel表中------------------*/
            //$i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
// 创建一个样式数组
        $styleArray = [
            'font' => [
                'bold' => true, // 加粗
                'size' => 16, // 字体大小
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, // 水平居中
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, // 垂直居中
            ],
        ];

// 应用样式到第一行
        $objSheet->getStyle('A1:X1')->applyFromArray($styleArray);
            for ($i = 2; $i <= $total+1; $i++) {
                $objSheet->setCellValue('A' . $i, $list[$i-2]['id'])
                    ->setCellValue('B' . $i, '编号：'.$list[$i-2]['order_no'])
                    ->setCellValue('C' . $i, $list[$i-2]['pay']['pay_no'])
                    ->setCellValue('D' . $i, $list[$i-2]['pay']['pay_type_text'])
                    ->setCellValue('E' . $i, $list[$i-2]['pay']['coupon_price'])
                    ->setCellValue('F' . $i, $list[$i-2]['pay']['order_price'])
                    ->setCellValue('G' . $i, $list[$i-2]['pay']['freight_price'])
                    ->setCellValue('H' . $i, $list[$i-2]['pay']['order_price'])
                    ->setCellValue('I' . $i, $list[$i-2]['pay']['refund_price'])
                    ->setCellValue('J' . $i, $list[$i-2]['pay']['order_price']-$list[$i-2]['pay']['refund_price'])
                    ->setCellValue('K' . $i, $list[$i-2]['state_text'])
//                    ->setCellValue('L' . $i, $list[$i-2]['pay']['order_price'])
                    ->setCellValue('L' . $i, $list[$i-2]['createtime_text'])
                    ->setCellValue('M' . $i, $list[$i-2]['paymenttime_text'])
                    ->setCellValue('N' . $i, $list[$i-2]['delivertime_text'])
                    ->setCellValue('O' . $i, $list[$i-2]['dealtime_text'])
                    ->setCellValue('P' . $i, $list[$i-2]['express_name'])
                    ->setCellValue('Q' . $i, $list[$i-2]['express_no'])
                    ->setCellValue('R' . $i, $list[$i-2]['remarks'])
                    ->setCellValue('S' . $i, $list[$i-2]['user']['id'])
                    ->setCellValue('T' . $i, $list[$i-2]['user']['nickname'])
                    ->setCellValue('U' . $i, $list[$i-2]['user']['mobile'])
                    ->setCellValue('V' . $i, $list[$i-2]['address']['name'])
                    ->setCellValue('W' . $i, $list[$i-2]['address']['mobile'])
                    ->setCellValue('X' . $i, $list[$i-2]['address']['address']);
//                    ->setCellValue('I' . $i, date('Y-m-d H:i:s',$sql[$i-2]['id']));
            }


            /*--------------下面是设置其他信息------------------*/
//            $title = date("Ymd-公摊详情");
//            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
//            header('Cache-Control: max-age=0');
//            $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
//            $objWriter->save('php://output');
//            return;

            $outputFileName = date("YmdHis") . '-导出订单.xlsx';
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:inline;filename="' . $outputFileName . '"');
            header("Content-Transfer-Encoding: binary");
            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Pragma: no-cache");
            $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
            $objWriter->save('php://output');
            exit;

//        }
    }


    /**
	 * 详情
	 */
	public function detail($id = null)
	{
		$row = $this->model->get($id);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		
		$row['address'] = model('app\api\model\wanlshop\OrderAddress')
			->where(['order_id' => $id])
			->order('isaddress desc')
			->field('id,name,mobile,address,address_name')
			->find();
			
		$row['pay'] = model('app\admin\model\wanlshop\Pay')
			->where(['order_id' => $row['id'], 'type' => 'goods'])
			->find();
			
		// 查询快递状态
		switch ($row['state']) {
			case 1:
				$express = [
					'context' => '付款后，即可将宝贝发出',
					'status' => '尚未付款',
					'time' => date('Y-m-d H:i:s', $row['createtime'])
				];
				break;
			case 2:
				$express = [
					'context' => '商家正在处理订单',
					'status' => '已付款',
					'time' => date('Y-m-d H:i:s', $row['paymenttime'])
				];
				break;
			default: // 获取物流
				$eData = model('app\api\model\wanlshop\KuaidiSub')
					->where(['express_no' => $row['express_no']])
					->find();
				// 获取数据 兼容PHP7.4	1.1.5升级
				if(!empty($eData['data'])){
					$ybData = json_decode($eData['data'], true);
					// 运单状态 1.0.6升级
					$statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
					$status = $statusText[0];
					if(in_array('status', $ybData[0])){
						$status = $ybData[0]['status'];
					}else{
						if($eData['ischeck'] === 1){
							$status = $statusText[3];
						}else{
							$status = $statusText[$eData['state']];
						}
					}
					$express = [
						'status' => $status,
						'context' => $ybData[0]['context'],
						'time' => $ybData[0]['time'],
					];
				}else{
					$express = [
						'status' => '已发货',
						'context' => '包裹正在等待快递小哥揽收~',
						'time' => date('Y-m-d H:i:s', $row['delivertime'])
					];
				}
		}
		$this->view->assign("kuaidi", $express);
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
	/**
	 * 快递查询
	 */
	public function relative($id = null)
	{
		$row = $this->model->get($id);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		$data = model('app\api\model\wanlshop\KuaidiSub')
			->where(['express_no' => $row['express_no']])
			->find();
		$list = [];
		$week = array(
		    "0"=>"星期日",
		    "1"=>"星期一",
		    "2"=>"星期二",
		    "3"=>"星期三",
		    "4"=>"星期四",
		    "5"=>"星期五",
		    "6"=>"星期六"
		);
		if($data){
			// 兼容PHP7.4	1.1.6升级
			if(!empty($data['data'])){
				foreach(json_decode($data['data'], true) as $vo){
					$list[] = [
						'time' => strtotime($vo['time']),
						'status' => in_array('status', $vo) ? $vo['status'] : '在途',  // 1.0.6升级
						'context' => $vo['context'],
						'week' => $week[date('w', strtotime($vo['time']))]
					];
				}
			}
		}
		$this->view->assign("week", $week);
		$this->view->assign("list", $list);
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
}
